import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { winPrizeStatusArrs } from '../recyc-market-manage.pipe';
import { CommonService } from '../../../../services-common/common.service';
import { LoveMakeupAwardPrizesService } from '../services/love-makeup-award-prizes.service';

@Component({
  selector: 'app-love-makeup-award-prizes',
  templateUrl: './love-makeup-award-prizes.component.html',
  styleUrls: ['./love-makeup-award-prizes.component.scss']
})
export class LoveMakeupAwardPrizesComponent implements OnInit {

  searchOptions: any = [
    { type: 1, labelText: '用户', valueKey: 'user', value: '', placeholder: '请输入用户ID/手机号' },
    { type: 1, labelText: '收款信息', valueKey: 'collectionInformation', value: '', placeholder: '请输入收款账号/真实姓名' },
    {
      type: 2,
      labelText: '归属活动',
      valueKey: 'activityId',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'id', label: 'activityName' },
      selectOptions: []
    },
    {
      type: 2,
      labelText: '有无收款信息',
      valueKey: 'haveAddress',
      value: [],
      multiple: false,
      notTostr: false,
      selectBindKey: { key: 'value', label: 'label' },
      selectOptions: [
        {value: 0, label: '无'},
        {value: 1, label: '有'}
      ],
    },
    {
      type: 2,
      labelText: '状态',
      valueKey: 'status',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'value', label: 'label' },
      selectOptions: [...winPrizeStatusArrs],
    },
    { type: 3, labelText: '中奖时间', valueKey: ['beginTime', 'endTime'], value: [], isTimeSelect: true },
    { type: 3, labelText: '发放时间', valueKey: ['grantTime', 'grantEndTime'], value: [], isTimeSelect: true },
  ];
  searchParams: any = {};

  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };

  ascriptionOptions: any[] = []; // 归属活动Options

  /**
   * 发放奖品 Modal
   * ----------------------------------------------------------------
   */
  isAwardPrizesVisible = false;
  awardPrizesLoading = false;
  awardPrizesId: any = null;
  awardPrizesRemark = '';
  // awardPrizesForm!: FormGroup;

  /**
   * 收款信息 Modal
   * ----------------------------------------------------------------
   */
  isCollectionVisible = false;
  collectionLoading = false;
  collectionItem: any = null;
  collectionForm!: FormGroup;

  /**
   * Table Check
   * ----------------------------------------------------------------
   */
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = [];
  setOfCheckedId = new Set<number>();

  // exportLoading
  exportLoading = false;

  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    private commonService: CommonService,
    private services: LoveMakeupAwardPrizesService
  ) { }

  ngOnInit(): void {
    this.collectionForm = this.fb.group({
      alipayAccount: ['', [Validators.required]],
      realName: ['', [Validators.required]]
    });

    this.loadGrantWinPrizeAttriActData();
  }

  // 查询归属活动list
  async loadGrantWinPrizeAttriActData() {
    let params = {
      page: 1,
      pageSize: 9999
    }
    const {code, data, message}: any = await this.services.grantWinPrizeAttriActData(params);

    if (code === 0) {
      this.ascriptionOptions = data.records || [];
      this.setSearchOption(data.records, 'activityId');
    } else {
      this.message.error(message);
    }
  }

  async loadTable() {
    let params = {
      ...this.searchParams,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize,
      source: 0
    }
    this.tableParams.loading = true;
    const {code, data, message}: any = await this.services.queryWinPrizeData(params);
    this.tableParams.loading = false;

    if (code === 0) {
      this.tableParams.tableData = data.records || [];
      this.tableParams.total = data.total || 0;
    } else {
      this.message.error(message);
    }
  }

  queryReasetData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }

  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  /**
   * ----------------------------------------------------------------
   * Table Check
   * ----------------------------------------------------------------
   */
  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData
      .filter(item => [0, 2].includes(item.status))
      .forEach(item => this.updateCheckedSet(item.id, value));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    let listOfCurrentPageData = this.listOfCurrentPageData.filter(item => [0, 2].includes(item.status));
    this.checked = listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id));
    this.indeterminate = listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }

  /**
   * ----------------------------------------------------------------
   * 发放奖品 Modal
   * ----------------------------------------------------------------
   */
  showAwardPrizesModal(id?: any) {
    if (!id && !this.setOfCheckedId.size) {
      this.message.warning('请先勾选所需发放奖品项');
      return
    }

    this.awardPrizesId = id ? id : null;
    this.awardPrizesRemark = '';
    this.isAwardPrizesVisible = true;
  }

  async submitAwardPrizesForm() {
    let params = {
      ids: this.commonService.isEmpty(this.awardPrizesId) ? [...this.setOfCheckedId] : [this.awardPrizesId],
      note: this.awardPrizesRemark,
      status: 1
    }
    this.awardPrizesLoading = true;
    const {code, message}: any = await this.services.grantWinPrizeData(params);
    this.awardPrizesLoading = false;

    if (code === 0) {
      this.isAwardPrizesVisible = false;
      this.message.success('发放成功');
      this.setOfCheckedId.clear();
      this.loadTable();
    } else {
      this.message.error(message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * 收款信息 Modal
   * ----------------------------------------------------------------
   */
  showCollectionModal(item?: any) {
    this.collectionItem = this.commonService.isEmpty(item) ? null : item;
    this.collectionForm.reset();

    if (!this.commonService.isEmpty(item)) {
      this.collectionForm.patchValue({
        alipayAccount: item.alipayAccount,
        realName: item.realName
      });
    }
    this.isCollectionVisible = true;
  }

  async submitCollectionForm() {
    if (this.collectionForm.valid) {
      let params = {
        id: this.collectionItem.id,
        haveAddress: 1,
        ...this.collectionForm.value
      }
      this.collectionLoading = true;
      const {code, message}: any = await this.services.updateWinPrizeInfoData(params);
      this.collectionLoading = false;

      if (code === 0) {
        this.isCollectionVisible = false;
        this.message.success('操作成功');
        this.loadTable();
      } else {
        this.message.error(message);
      }
    } else {
      Object.values(this.collectionForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  // 导出Table
  async exportTable() {
    this.exportLoading = true;
    const res: any = await this.services.exportWinPrizeData({...this.searchParams, source: 1});
    this.exportLoading = false;

    if (res.type === 'application/octet-stream') {
      this.commonService.downLoadBlobFile(res, '用户中奖信息');
    } else {
      this.message.error('导出失败');
    }
  }

  setSearchOption(array: Array<any>, val: string) {
    let temIndex = this.searchOptions.findIndex((item: any) => item.valueKey === val);
    this.searchOptions[temIndex].selectOptions = array || [];
  }
}
